package com.ruoyi.swla2.controller;

import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.Hutool;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CoordinateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.swla2.domain.GisPoint;
import com.ruoyi.swla2.service.IGisPointService;
import com.ruoyi.swla2.util.JtsUtils;
//import com.ruoyi.swla2.util.WKTTransform;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.io.ParseException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.swla2.domain.GisLine;
import com.ruoyi.swla2.service.IGisLineService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * GIS管网-管线Controller
 *
 * @author gdqt
 * @date 2023-11-26
 */
@RestController
@RequestMapping("/swla2/gisLine")
public class GisLineController extends BaseController {
    @Autowired
    private IGisLineService gisLineService;

    @Autowired
    private IGisPointService gisPointService;

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/test")
    public void test() {
        File file = FileUtil.file("C:\\Users\\1\\Desktop\\nx_wkt.txt");
        List<String> fileLines = FileUtil.readLines(file, "UTF-8");
        List<String> geomLines = fileLines.stream().map(item -> item.substring(0, item.indexOf("))") + 2)).collect(Collectors.toList());
        System.out.println("线：" + geomLines.size());

        geomLines.forEach(item -> {
//            Geometry geometry = WKTTransform.coordinateTransform(item, 4547, 4326);
//            Coordinate[] coordinates = geometry.getCoordinates();
//            Coordinate start = coordinates[0];
//            String startStr = "POINT(" + start.getX() + " " + start.getY() + ")";
//
//            Coordinate end = coordinates[coordinates.length - 1];
//            String endStr = "POINT(" + end.getX() + " " + end.getY() + ")";
//
//            GisPoint startPoint = gisPointService.getByGeom(startStr);
//            GisPoint endPoint = gisPointService.getByGeom(endStr);
//
//            GisLine line = new GisLine();
//            line.setLayerId(6);
//            line.setsPoint(startPoint.getExpNo());
//            line.setePoint(endPoint.getExpNo());
//            line.setGeom(geometry.toString());
//            gisLineService.insertGisLine(line);
        });
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/testDygq")
    public void testDygq() {
        File file = FileUtil.file("C:\\Users\\1\\Desktop\\dygq_wkt.txt");
        List<String> fileLines = FileUtil.readLines(file, "UTF-8");
        fileLines.forEach(line -> {
            try {
                LineString lineString = JtsUtils.createLineStringByWKT(line);
                System.out.println("MULTI" + lineString.toString().replace("(", "((").replace(")", "))"));
                Coordinate[] coordinates = lineString.getCoordinates();
                Coordinate start = coordinates[0];
                String startStr = "POINT(" + start.getX() + " " + start.getY() + ")";
                System.out.println(startStr);
                Coordinate end = coordinates[coordinates.length - 1];
                String endStr = "POINT(" + end.getX() + " " + end.getY() + ")";
                System.out.println(endStr);
                GisPoint startPoint = gisPointService.getByGeom(startStr);
                GisPoint endPoint = gisPointService.getByGeom(endStr);

                GisLine gisLine = new GisLine();
                gisLine.setLayerId(25);
                gisLine.setsPoint(startPoint.getExpNo());
                gisLine.setePoint(endPoint.getExpNo());
                gisLine.setGeom("MULTI" + lineString.toString().replace("(", "((").replace(")", "))"));
                gisLineService.insertGisLine(gisLine);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });

//        geomLines.forEach(item -> {
//            Geometry geometry = WKTTransform.coordinateTransform(item, 4547, 4326);
//            Coordinate[] coordinates = geometry.getCoordinates();
//            Coordinate start = coordinates[0];
//            String startStr = "POINT(" + start.getX() + " " + start.getY() + ")";
//
//            Coordinate end = coordinates[coordinates.length - 1];
//            String endStr = "POINT(" + end.getX() + " " + end.getY() + ")";
//
//            GisPoint startPoint = gisPointService.getByGeom(startStr);
//            GisPoint endPoint = gisPointService.getByGeom(endStr);
//
//            GisLine line = new GisLine();
//            line.setLayerId(6);
//            line.setsPoint(startPoint.getExpNo());
//            line.setePoint(endPoint.getExpNo());
//            line.setGeom(geometry.toString());
//            gisLineService.insertGisLine(line);
//        });
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @PostMapping("/getPipeLengthData")
    public AjaxResult getPipeLengthData(@RequestBody Map<String, Object> queryMap) {
        List<GisLine> gisLineList = gisLineService.getPipeLengthData(queryMap);
        gisLineList.forEach(item -> {
            try {
                item.setLineLength(NumberUtil.round(JtsUtils.distance(JtsUtils.createMultiLineStringByWKT(item.getGeom())), 2).doubleValue());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });
        return success(gisLineList);
    }

    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @PostMapping("/getLineAlarmData")
    public AjaxResult getLineAlarmData(@RequestBody Map<String, Object> queryMap) {
        System.out.println(queryMap);
        LocalDate now = LocalDate.now();
        LocalDate mDate = now.minusYears(Long.valueOf(queryMap.get("featureYears").toString()));
        queryMap.put("mDate", mDate);
        List<GisLine> gisLineList = gisLineService.getLineAlarmData(queryMap);
        return success(gisLineList);
    }

    /**
     * 查询GIS管网-管线列表
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping("/list")
    public TableDataInfo list(GisLine gisLine) {
        List<GisLine> list = gisLineService.selectGisLineList(gisLine);
        list.forEach(item -> {
            JSONObject geomObj = JSON.parseObject(item.getGeom());
            String rGeom = geomObj.getString("coordinates").replace("[[[", "[[").replace("]]]", "]]")
                    .replace("]],[[", "],[");
            item.setCoordinates(rGeom);
        });
        return getDataTable(list);
    }

    /**
     * 导出GIS管网-管线列表
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管线", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GisLine gisLine) {
        List<GisLine> list = gisLineService.selectGisLineList(gisLine);
        ExcelUtil<GisLine> util = new ExcelUtil<GisLine>(GisLine.class);
        util.exportExcel(response, list, "GIS管网-管线数据");
    }

    /**
     * 获取GIS管网-管线详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(gisLineService.selectGisLineById(id));
    }

    /**
     * 新增GIS管网-管线
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管线", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GisLine gisLine) {
        return toAjax(gisLineService.insertGisLine(gisLine));
    }

    /**
     * 修改GIS管网-管线
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管线", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GisLine gisLine) {
        gisLine.setCoordinates(gisLine.getCoordinates().replace("\"", ""));
        GisLine record = gisLineService.selectGisLineById(gisLine.getId());
        JSONObject geomObj = JSON.parseObject(record.getGeom());
        String rGeom = geomObj.getString("coordinates").replace("[[[", "[[").replace("]]]", "]]")
                .replace("]],[[", "],[");

        System.out.println("记录：" + rGeom);
        System.out.println(gisLine.getCoordinates());
        System.out.println("原始：" + gisLine.getGeom());
        String nGeom = gisLine.getCoordinates().replace("],[", "@").replace(",", " ").replace("@", ", ")
                .replace("[[", "((").replace("]]", "))");
        gisLine.setGeom("MultiLineString " + nGeom);
        System.out.println("替换：" + gisLine.getGeom());
        if (!rGeom.equals(gisLine.getCoordinates())) {
            JSONArray jsonArrayOld = JSON.parseArray(rGeom);
            String[] sPointsOld = jsonArrayOld.get(0).toString().replace("[", "").replace("]", "").split(",");
            String[] ePointsOld = jsonArrayOld.get(jsonArrayOld.size() - 1).toString().replace("[", "").replace("]", "").split(",");

            JSONArray jsonArrayNew = JSON.parseArray(gisLine.getCoordinates());
            // 经纬度改变
            String[] sPointsNew = jsonArrayNew.get(0).toString().replace("[", "").replace("]", "").split(",");
            GisPoint startPoint = new GisPoint();
            startPoint.setExpNo(gisLine.getsPoint());
            startPoint.setX(Double.valueOf(sPointsNew[0]));
            startPoint.setY(Double.valueOf(sPointsNew[1]));
            startPoint.setGeom("POINT(" + sPointsNew[0] + " " + sPointsNew[1] + ")");
            gisPointService.updateGisPointByExpNo(startPoint);
            gisLineService.updateGisLinePointsXY(gisLine.getsPoint(), sPointsOld[0] + " " + sPointsOld[1], sPointsNew[0] + " " + sPointsNew[1]);

            String[] ePointsNew = jsonArrayNew.get(jsonArrayNew.size() - 1).toString().replace("[", "").replace("]", "").split(",");
            GisPoint endPoint = new GisPoint();
            endPoint.setExpNo(gisLine.getePoint());
            endPoint.setX(Double.valueOf(ePointsNew[0]));
            endPoint.setY(Double.valueOf(ePointsNew[1]));
            endPoint.setGeom("POINT(" + ePointsNew[0] + " " + ePointsNew[1] + ")");
            gisPointService.updateGisPointByExpNo(endPoint);
            gisLineService.updateGisLinePointsXY(gisLine.getePoint(), ePointsOld[0] + " " + ePointsOld[1], ePointsNew[0] + " " + ePointsNew[1]);
        }

        if (!NumberUtil.equals(record.getsDeep(), gisLine.getsDeep())) {
            // 起点埋深改变
            gisLineService.updateGisLinePointsDeep(record.getsPoint(), gisLine.getsDeep());
        }

        if (!NumberUtil.equals(record.geteDeep(), gisLine.geteDeep())) {
            // 终点埋深改变
            gisLineService.updateGisLinePointsDeep(record.getePoint(), gisLine.geteDeep());
        }

        return toAjax(gisLineService.updateGisLine(gisLine));
    }

    /**
     * 删除GIS管网-管线
     */
    @PreAuthorize("@ss.hasAnyPermi('pipe:manage,pipe:analysis')")
    @Log(title = "GIS管网-管线", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(gisLineService.deleteGisLineByIds(ids));
    }

    public static void main(String[] args) {
        System.out.println("[[113.694193,23.273449],[113.69517909291743,23.273470644762167]]".replace("],[", "@").replace(",", " ").replace("@", ", ").replace("[[", "((").replace("]]", "))"));
    }
}
